package game.module.mj.processor;

import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.common.ErrorCodeConstants;
import game.common.PlayingRoleMsgProcessor;
import game.entity.PlayingRole;
import game.module.hall.logic.CheatManager;
import game.module.mj.bean.MjRoom;
import game.module.mj.logic.MjDataManager;
import lion.common.MsgCodeAnn;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lua.LuaMessageLogin.S2ErrorCode;
import lua.LuaMessageMj.C2SMJJoinRoomCheck;
import lua.LuaMessageMj.S2CMJJoinRoomCheck;

@MsgCodeAnn(msgcode = C2SMJJoinRoomCheck.id, accessLimit = 500)
public class MjJoinRoomCheckProcessor extends PlayingRoleMsgProcessor {

	private static Logger logger = LoggerFactory.getLogger(MjJoinRoomCheckProcessor.class);

	@Override
	public void process(PlayingRole hero, RequestMessageRaw request) throws Exception {
		C2SMJJoinRoomCheck reqMsg = C2SMJJoinRoomCheck.parse(request);
		String room_id = reqMsg.room_id;
		int playerId = hero.getId();
		logger.info("mj join room check,playeyId={},room_id={}", playerId, room_id);
		// 是否在房间中
		boolean isInRoom = MjDataManager.getInstance().isPlayerInRoom(playerId);
		if (isInRoom) {
			S2ErrorCode respMsg = new S2ErrorCode(102);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		// is fang not exist
		if (!MjDataManager.getInstance().checkRoomExist(room_id)) {
			S2ErrorCode respMsg = new S2ErrorCode(104);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		final MjRoom mjRoom = MjDataManager.getInstance().getMjRoom(room_id);

		if (CheatManager.getInstance().checkCheatAndPush(mjRoom.getPrevent_cheat(), mjRoom.getIps(), hero)) {
			return;
		}
		// 人数已满
		if (mjRoom.getPlayerList().size() >= 4) {
			S2ErrorCode respMsg = new S2ErrorCode(105);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		// ret
		S2CMJJoinRoomCheck respMsg = new S2CMJJoinRoomCheck();
		hero.writeAndFlush(respMsg.build(hero.alloc()));
	}

	@Override
	public void processProto(PlayingRole playingRole, RequestProtoMessage request) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void processWebsocket(PlayingRole playingRole, MyRequestMessage request) throws Exception {
		// TODO Auto-generated method stub

	}

	public String getIpAddr(String ipAddrRaw) {
		String retStr = ipAddrRaw;
		int fenIndex = ipAddrRaw.indexOf(":");
		if (fenIndex >= 0) {
			retStr = retStr.substring(0, fenIndex);
		}
		if (retStr.startsWith("/")) {
			retStr = retStr.substring(1);
		}
		return retStr;
	}
}
